package com.smarthome.rpc.sms;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Properties;

import org.apache.log4j.Logger;

import redis.clients.jedis.Client;

import com.smarthome.rpc.base.BaseRpcService;

public class SmsClient extends BaseRpcService{
	private static final Logger logger = Logger.getLogger(SmsClient.class);
	
	public final static String SUCCESS_CODE = "100";//成功
	public final static String FAIL_CODE = "101";//失败
	public final static String PWDERROR_CODE = "102"; //验证失败(密码不对)
	public final static String NUMBERERROR_CODE = "103"; //号码有错(接收号码格式错误)
	public final static String CONTENT_ERROR_CODE = "104";//内容有错(敏感内容)
	public final static String DOFAST_CODE = "105";//操作频率过快(每秒十次)

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	/*
	 * webservice服务器定义
	 */
	// java.io.IOException: Server returned HTTP response code: 400 for URL: http://sdk.entinfo.cn:8060/webservice.asmx。
	// 如果出现上述400错误，请参考第102行。
	// 如果您的系统是utf-8，收到的短信可能是乱码，请参考第102，295行
	// 可以根据您的需要自行解析下面的地址
	// http://sdk2.zucp.net:8060/webservice.asmx?wsdl
	//private String serviceURL = "http://sdk.entinfo.cn:8060/webservice.asmx";

	private static String _uc = "";// 序列号
	private static String pwd = "";// 密码
	private static String _host = ""; //url
	private static String sign = "【多啦家园】";

	private final static String FILENAME = "/SMS.properties";
	
	
	private final static String NOFIELEXCEPTION = String.format("%s文件不存在",FILENAME);
	
	
	
	static{
		Properties p = new Properties();
		InputStream in = Client.class.getResourceAsStream(FILENAME);
		try {
			p.load(in);
			_uc = p.getProperty("sn");
			_host = p.getProperty("host");
			pwd = MD5Encode( p.getProperty("pwd"));
		}	catch (IOException e) {
			LOGGER.info(e.getMessage());
			new IllegalArgumentException(NOFIELEXCEPTION);
		}
	}
	
	/**
	 * 发送短信
	 * 
	 * @param mobiles
	 *            String 接收号码
	 * @param cont
	 *            String 短信内容
	 * @param msgid
	 *            String 短信ID
	 * @return String
	 */
	public  synchronized static String sendSMS(String mobiles, String cont, String msgid) {
		String re = "";
		try {
			cont = URLEncoder.encode(String.format("%s%s",cont,sign), "GBK"); // 短信内容需要编码
			String sendUrl = _host + "cmd=send&uid=" + _uc + "&psw="
					+ pwd + "&mobiles=" + mobiles + "&msgid="
					+ msgid + "&msg=" + cont + " ";
			
			re = submit(sendUrl);
		} catch (Exception ex) {
			logger.info(ex.getMessage());
		}
		return re;
	}

	/**
	 * 接收短信
	 * 
	 * @return String
	 */
	public synchronized static String getMO() {
		String re = "";
		try {
			String moUrl = _host + "cmd=getmo&uid=" + _uc + "&psw="
					+pwd+ "";
			re = submit(moUrl);
		} catch (Exception ex) {

		}
		return re;
	}

	/**
	 * 取发送状态
	 * 
	 * @return String
	 */
	public synchronized static String getStatus() {
		String getstatusUrl = _host + "cmd=getstatus&uid=" + _uc + "&psw="
				+pwd + "";
		return submit(getstatusUrl);
	}

	/**
	 * GET提交
	 * 
	 * @param url
	 *            String
	 * @return String
	 */
	private static String submit(String url) {
		logger.info(String.format("调用短息发送接口开始:%s",url));
		String re = "";
		int byteMax = 50;
		try {
			URL myurl = new URL(url);
			URLConnection urlcon = myurl.openConnection();
			urlcon.setUseCaches(false);
			urlcon.connect();
			InputStream inputstream = urlcon.getInputStream();
			byte[] buff = new byte[byteMax];
			ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
			int ins;
			while ((ins = inputstream.read(buff)) >= 0) {
				bytearrayoutputstream.write(buff, 0, ins);
			}
			re = new String(bytearrayoutputstream.toByteArray());
			re.trim();
		} catch (MalformedURLException ex) {
			logger.info(ex.getMessage());
		} catch (IOException ex) {
			logger.info(ex.getMessage());
		}
		logger.info(String.format("短息回执码：%s", re));
		return re;
	}

	/**
	 * MD5加密
	 * 
	 * @param origin
	 * @return
	 */
	private static String MD5Encode(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (Exception ex) {

		}
		return resultString;
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	public static void main(String[] args) {
		String str = getStatus();
		String[] arr = str.split("\n");
		int i = 0;
		for(String s : arr){
			System.out.println(i++);
			System.out.println(s);
		}
		
	}
	
	

}
